package cn.ryh.designpatterndemo.compositepattern;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ComponentComposite
 * @Description 模拟组合模式
 * @Author RaoYH
 * @Date 2019/4/26
 */
public class ComponentComposite {
    // 父节点
    private ComponentComposite parent = null;
    // 名字
    private String name;

    // 子节点 一个节点可以有多个子节点
    private List<ComponentComposite> children = new ArrayList<>();

    public ComponentComposite(String name) {
        this.name = name;
    }

    public ComponentComposite getParent() {
        return parent;
    }

    public void setParent(List<ComponentComposite> children) {
        for (ComponentComposite child : children) {
            child.parent = this;
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<ComponentComposite> getChildren() {
        return children;
    }

    public void setChildren(List<ComponentComposite> children) {
        this.children = children;
    }

    @Override
    public String toString() {
        StringBuilder childrenStr = new StringBuilder();
        if (this.children.isEmpty()) {
            childrenStr = new StringBuilder(" [] ");
        }
        for (int i = 0; i < children.size(); i++) {
            childrenStr.append(children.get(i).getName());
            if (i == children.size() - 1) {
                childrenStr.append("]");
            } else {
                childrenStr.append(", ");
            }
        }
        String parent = "";
        if (this.parent == null) {
            parent = null;
        } else {
            parent = this.parent.name;
        }
        return "SecurityComponent{" +
                "parent='" + parent + '\'' +
                ", name='" + name + '\'' +
                ", children=" + childrenStr +
                '}';
    }

    public void setChildrenAndParent(ComponentComposite securityComponent) {
        this.children.add(securityComponent);
        securityComponent.parent = this;
    }
}